package model

import (
	"ginblog/model/request"
	"gorm.io/gorm"
	"time"
)

type Category struct {
	ID         uint      `gorm:"primary_key" json:"id"`
	Name       string    `gorm:"type:varchar(20);not null" json:"name"`
	Deleted    uint      `gorm:"int" json:"-"`
	CreateTime time.Time `gorm:"column:created_time" json:"create_time"`
}

func (this *Category) TableName() string {
	return "category"
}

// 获取单个
func (this *Category) Get() error {
	return db.Where("id = ?", this.ID).First(this).Error
}

// 添加,返回影响行数和错误信息
func (this *Category) Create() (int64, error) {
	tx := db.Omit("created_time").Create(this)
	return tx.RowsAffected, tx.Error
}

func (this *Category) Update(m map[string]interface{}) (int64, error) {
	tx := db.Model(this).Where("id = ?", this.ID).Omit("password").Updates(m)
	return tx.RowsAffected, tx.Error
}

func (this *Category) Delete() (int64, error) {
	tx := db.Model(this).UpdateColumn("deleted", 1)
	return tx.RowsAffected, tx.Error
}

func (this *Category) Remove() (int64, error) {
	tx := db.Unscoped().Delete(this)
	return tx.RowsAffected, tx.Error
}
func CountCateGory(m ...map[string]interface{}) (int64, error) {
	var (
		count int64
	)

	tx := db.Model(&Category{}).Where("deleted = ?", 0).Count(&count)
	return count, tx.Error
}
func GetCateGoryList(page *request.PageParam) (categories []Category, err error, a int64) {
	var (
		total int64
	)
	err = db.Model(&Category{}).Limit(page.PageSize).Offset((page.PageNum-1)*page.PageSize).Where("deleted = ?", 0).Order("created_time desc").Count(&a).Find(&categories).Error
	db.Model(&User{}).Count(&total)
	if err != nil && err != gorm.ErrRecordNotFound {
		return
	}
	return categories, nil, a
}
